import { getProductListAdmin, uploadImageAdmin, editProductAdmin, createProductAdmin, deleteProductAdmin, saveProductDetailAdmin, recoverProductAdmin } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Modal, ModalHeader, ModalBody, Form, Label, Button, List, Tooltip, ButtonGroup, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';
import { unkownImage } from '../../../../public/assets/images/unkownImage/default768A864.jpg'
import * as XLSX from 'xlsx';

const AdminProductListPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const maxImgSize = 1024 * 1024;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;
  const [loading, setLoading] = useState(false);

  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const [isOpen, setIsOpen] = useState(false);
  const [imgList, setImgList] = useState([]);
  const [imgBase64List, setImgBase64List] = useState([]);
  const [imgModalIsOpen, setImgModalIsOpen] = useState(false);
  const [imgName, setImgName] = useState("");
  const [addProductModal, setAddProductModal] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [pageCount, setPageCount] = useState(1);
  const [filter, setFilter] = useState(-1);
  const [detailModal, setDetailModal] = useState(false);
  const [detailList, setDetailList] = useState([]);
  const [file, setFile] = useState(null);

  const [deleteId, setDeleteId] = useState("");
  const [confirmModel, setConfirmModel] = useState(false);

  const [recoverModel, setRecoverModel] = useState(false);
  const [recoverId, setRecoverId] = useState("");

  const [detail, setDetail] = useState({
    "year": "",
    "brand": "",
    "model": "",
    "engine": "",
    "fuel_type": "",
  });

  const [formData, setFormData] = useState({
    "product_id": "",
    "product_name": "",
    "product_price": "",
    "product_quantity": "",
    "year": "",
    "brand": "",
    "model": "",
    "engine": "",
    "fuel_type": "",
    "upload_date": "",
    "product_detail": "",
    "product_description": "",
    "product_media1": "",
    "product_media2": "",
    "product_media3": "",
  });

  const [submitFormData, setSubmitFormData] = useState({
    "product_id": "",
    "product_name": "",
    "product_price": "",
    "product_num": "",
    "product_detail": "",
    "product_description": ""
  });

  const [keyword, setKeyword] = useState("");

  const debounceRef = useRef(null);
  const router = useRouter();

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getProductListAdmin({
          "keyword": "",
          "filter": filter.toString(),
          "pageNum": "1",
          "pageSize": "10"
        }).then(res => {
          setList(res.data);
          setPageCount(res.page_count)
        });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var product = localStorage.getItem("XYCLogin")
    if (!product) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

    debounceRef.current = debounce((item, quantity) => {
      changeProductCount({
        product_id: item.product_id,
        quantity: quantity
      })
    }, 1000);

    return () => {
      if (debounceRef.current) {
        debounceRef.current.cancel();
      }
    };
  }, [])

  const handleQtyUpdate = (item, quantity) => {
    if (quantity > 0 && quantity) {
      debounceRef.current(item, quantity);
      var newQtys = [];
      qtyList.map(q => {
        if (q.product_id != item.product_id)
          newQtys.push(q);
      });
      newQtys.push({
        "product_id": item.product_id,
        "quantity": quantity,
        "product_stock": item.product_stock,
        "price": item.price
      });
      setQtyList(newQtys);

      var newTotal = 0;
      newQtys.map(nq => {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      })
      setTotal(getTwoDecimal(`${newTotal}`))
    }
  };

  const removeProduct = (item) => {
    setList(v => v.filter(p => p.product_id != item.product_id));
    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
    var newTotal = 0;
    qtyList.map(nq => {
      if (nq.product_id != item.product_id) {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      }
    })
    setQtyList(v => v.filter(p => p.product_id != item.product_id));
    setTotal(getTwoDecimal(`${newTotal}`));
  }

  const handleFileChange = (event) => {
    // event.target.files 是一个 FileList 对象，它包含了用户选择的文件
    if (event.target.value != "" && imgList.length < 3) {
      var file = event.target.files[0];
      if (isImageFile(event.target.value)) {
        if (file.size < maxImgSize) {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            var base64 = reader.result.replace(/^data:image\/\w+;base64,/, '');
            if (base64 != undefined) {
              if (base64.length > 0) {
                setImgBase64List(imgs => [...imgs, base64])
              }
            }
          };
          setImgList(imgs => [...imgs, event.target.value])
        }
        else {
          toast.error("Image Can Not Larger Then 1 MB!")
        }
      };
    }
  };

  const isImageFile = (filename) => {
    const extensions = ['.jpg', '.jpeg', '.png'];
    return extensions.some(extension => filename.toLowerCase().endsWith(extension));
  }

  const handleUploadBtnOnclick = () => {
    document.getElementById("uploadRealBtn").click();
  }

  const handleDeleteImageItem = (id) => {
    setImgList(imgs => {
      return imgs.filter((v, index) => index != id);
    });
    setImgBase64List(imgs => {
      return imgs.filter((v, index) => index != id);
    });
  }

  const DeleteDetail = (id) => {
    setDetailList(detail => {
      return detail.filter((v, index) => index != id);
    })
  }

  const EditProductAdmin = (item) => {
    setFormData({
      "product_id": item.product_id,
      "product_name": item.product_name,
      "product_price": item.product_price,
      "product_quantity": item.product_num,
      "year": item.year,
      "brand": item.brand,
      "model": item.model,
      "engine": item.engine,
      "fuel_type": item.fuel_type,
      "upload_date": item.upload_date,
      "product_detail": item.product_detail,
      "product_description": item.product_description,
      "product_media1": item.product_media1,
      "product_media2": item.product_media2,
      "product_media3": item.product_media3,
    });

    setSubmitFormData({
      "product_id": item.product_id,
      "product_name": item.product_name,
      "product_price": item.product_price,
      "product_num": item.product_num,
      "product_detail": item.product_detail,
      "product_description": item.product_description,
    });

    setDetailList(item.product_details)

    var list = [];
    var base64List = [];
    if (item.product_media1) {
      list.push(item.product_media1);
      base64List.push("");
    }
    if (item.product_media2) {
      list.push(item.product_media2);
      base64List.push("");
    }
    if (item.product_media3) {
      list.push(item.product_media3);
      base64List.push("");
    }
    setImgList(list);
    setImgBase64List(base64List);
    setIsOpen(true);
  }

  const AddProductDetail = () => {
    setDetailList(details => [...details, detail]);
    setDetailModal(false);
  }

  const SaveProductInfo = () => {
    // console.log(submitFormData)
    if (imgList.length < 3) {
      toast.warning("At Least Three Images Are Required.")
    }
    else if (detailList.length < 1) {
      toast.warning("At Least One Detail Required.")
    }
    else {
      setLoading(true);
      editProductAdmin({
        "product_id": submitFormData.product_id.toString(),
        "product_name": submitFormData.product_name,
        "product_price": submitFormData.product_price,
        "product_num": submitFormData.product_num,
        "product_detail": submitFormData.product_detail,
        "product_description": submitFormData.product_description,
      }).then(res => {
        if (res.error_code == 2000) {
          saveProductDetailAdmin({
            "product_id": submitFormData.product_id.toString(),
            "product_details": detailList
          }).then(resa => {
            if (resa.error_code == 2000) {
              uploadImageAdmin({
                "product_id": submitFormData.product_id.toString(),
                "product_media1": imgList[0],
                "product_media2": imgList[1],
                "product_media3": imgList[2],
                "product_media1_base64": imgBase64List[0],
                "product_media2_base64": imgBase64List[1],
                "product_media3_base64": imgBase64List[2]
              }).then(resd => {
                if (resd.error_code == 2000) {
                  toast.success("Edit Product Succeed.");
                  location.reload();
                }
                else {
                  toast.error(resd.msg);
                  setLoading(false);
                }
              })
            }
            else {
              toast.error(resa.msg);
              setLoading(false);
            }
          })
        }
        else {
          toast.error(res.msg);
          setLoading(false);
        }
      })
    }
  }

  const onSubmitFormChange = (e) => {
    setSubmitFormData({ ...submitFormData, [e.target.name]: e.target.value });
  }

  const onSubmitDetailFormChange = (e) => {
    setDetail({ ...detail, [e.target.name]: e.target.value });
  }

  const onKeywordChange = (e) => {
    setKeyword(e.target.value);
  }

  const AddProduct = () => {
    setImgList([]);
    setImgBase64List([]);
    setFormData({
      "product_id": "",
      "product_name": "",
      "product_price": "",
      "product_quantity": "",
      "year": "",
      "brand": "",
      "model": "",
      "engine": "",
      "fuel_type": "",
      "upload_date": "",
      "product_detail": "",
      "product_description": "",
      "product_media1": "",
      "product_media2": "",
      "product_media3": ""
    });
    setSubmitFormData({
      "product_id": "",
      "product_name": "",
      "product_price": "",
      "product_num": "",
      "year": "",
      "brand": "",
      "model": "",
      "engine": "",
      "fuel_type": "",
      "product_detail": "",
      "product_description": ""
    });
    setAddProductModal(true);
  }

  const SaveNewProduct = () => {
    if (imgList.length < 3) {
      toast.warning("At Least Three Images Are Required.")
    }
    else if (detailList.length < 1) {
      toast.warning("At Least One Detail Required.")
    }
    else {
      setLoading(true);
      createProductAdmin({
        "product_name": submitFormData.product_name,
        "product_price": submitFormData.product_price,
        "product_num": submitFormData.product_num,
        // "year": submitFormData.year,
        // "brand": submitFormData.brand,
        // "model": submitFormData.model,
        // "engine": submitFormData.engine,
        // "fuel_type": submitFormData.fuel_type,
        "product_detail": submitFormData.product_detail,
        "product_description": submitFormData.product_description,
      }).then(res => {
        if (res.error_code == 2000) {
          saveProductDetailAdmin({
            "product_id": res.product_id.toString(),
            "product_details": detailList
          }).then(resa => {
            if (resa.error_code == 2000) {
              uploadImageAdmin({
                "product_id": res.product_id.toString(),
                "product_media1": imgList[0],
                "product_media2": imgList[1],
                "product_media3": imgList[2],
                "product_media1_base64": imgBase64List[0],
                "product_media2_base64": imgBase64List[1],
                "product_media3_base64": imgBase64List[2]
              }).then(resd => {
                if (resd.error_code == 2000) {
                  toast.success("Edit Product Succeed.");
                  location.reload();
                }
                else {
                  toast.error(resd.msg);
                  setLoading(false);
                }
              });
            }
            else {
              toast.error(resa.msg);
              setLoading(false);
            }
          })
        }
        else {
          toast.error(res.msg);
          setLoading(false);
        }
      })
    }
  }

  const SearchProduct = () => {
    getProductListAdmin({
      "keyword": keyword,
      "filter": filter.toString(),
      "pageNum": "1",
      "pageSize": "10"
    }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }

  const AddPage = () => {
    if (pageNum < pageCount) {
      getProductListAdmin({
        "keyword": keyword,
        "filter": filter.toString(),
        "pageNum": pageNum + 1,
        "pageSize": "10"
      }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      });
      setPageNum(pageNum + 1);
    }
  }

  const MinusPage = () => {
    if (pageNum > 1) {
      getProductListAdmin({
        "keyword": keyword,
        "filter": filter.toString(),
        "pageNum": pageNum - 1,
        "pageSize": "10"
      }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      });
      setPageNum(pageNum - 1);
    }
  }

  const ChangeFilter = (filterNum) => {
    setFilter(filterNum);
    getProductListAdmin({
      "keyword": keyword,
      "filter": `${filterNum}`,
      "pageNum": `${pageNum}`,
      "pageSize": "10"
    }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }

  const DeleteProduct = (id) => {
    if (id) {
      deleteProductAdmin({
        id: id.toString()
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Delete Succeed.");
          location.reload();
        }
        else {
          toast.error(res.msg);
        }
      })
    }
  }

  const RecoverProduct = () => {
    recoverProductAdmin({ id: `${recoverId}` }).then(res => {
      if (res.error_code == "2000") {
        toast.success("Recover Succeed.");
        location.reload();
      }
      else {
        toast.error(res.msg);
      }
    })
  }

  const handleExcelFileChange = (e) => {
    if (e.target.value != "") {
      var file = e.target.files[0];
      const readerExcel = new FileReader();
      readerExcel.readAsArrayBuffer(file);
      readerExcel.onload = (excel) => {
        const data = new Uint8Array(excel.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        if (jsonData) {
          setDetailList(jsonData.map(item => {
            return {
              "year": item.year.toString(),
              "brand": item.brand.toString(),
              "model": item.model.toString(),
              "engine": item.engine.toString(),
              "fuel_type": item.fuel_type.toString()
            };
          }));
        }
      };
    }
  };

  const handleExcelUploadOnclick = () => {
    document.getElementById("uploadExcelRealBtn").click();
  }

  const handleDwonloadTempExcel = () => {
    const wb = XLSX.utils.book_new();
    const data = [["year", "brand", "model", "engine", "fuel_type"]];

    // 将数据转换为工作表
    const ws = XLSX.utils.aoa_to_sheet(data);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    // 写入文件
    XLSX.writeFile(wb, "example.xlsx");
  }

  return (
    <div>
      <Modal isOpen={recoverModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to recover product?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setRecoverModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { RecoverProduct() }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>


      <Modal isOpen={confirmModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to delete product?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setConfirmModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { DeleteProduct(deleteId) }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>
      <Modal isOpen={detailModal} centered size="lg">
        <ModalHeader >Product Detail</ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col md="4">
                <Label for="fname">Year</Label>
                <Input type="text" className="form-control" id="year" name="year" defaultValue={formData.year} placeholder="Year" onChange={onSubmitDetailFormChange} />
              </Col>
              <Col md="4">
                <Label for="fname">Brand</Label>
                <Input type="text" className="form-control" id="brand" name="brand" defaultValue={formData.brand} placeholder="Brand" onChange={onSubmitDetailFormChange} />
              </Col>
              <Col md="4">
                <Label for="fname">Model</Label>
                <Input type="text" className="form-control" id="model" name="model" defaultValue={formData.model} placeholder="Model" onChange={onSubmitDetailFormChange} />
              </Col>
            </Row>
            <Row>
              <Col md="4">
                <Label for="fname">Engine</Label>
                <Input type="text" className="form-control" id="engine" name="engine" defaultValue={formData.engine} placeholder="Engine" onChange={onSubmitDetailFormChange} />
              </Col>
              <Col md="4">
                <Label for="fname">Fuel Type</Label>
                <Input type="text" className="form-control" id="fuel_type" name="fuel_type" defaultValue={formData.fuel_type} placeholder="Fuel Type" onChange={onSubmitDetailFormChange} />
              </Col>
            </Row>
            <div className="admin-user-form-btn-list">
              <Row>
                <Col md="6">
                </Col>
                <Col md="3">
                  <Button color="primary" style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} onClick={AddProductDetail}>Add</Button>
                </Col>
                <Col md="3">
                  <Button onClick={() => {
                    setDetailModal(false); setDetail({
                      "year": "",
                      "brand": "",
                      "model": "",
                      "engine": "",
                      "fuel_type": "",
                    })
                  }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} >Cancel</Button>
                </Col>
              </Row>
            </div>
          </div>
        </ModalBody>
      </Modal>
      <Modal isOpen={imgModalIsOpen} centered size="lg">
        <ModalHeader >Image Viewer</ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <img src={imgName != "" ? `${fileServerUrl}/${imgName}` : `${fileServerUrl}/products/default.jpg`} width={"100%"} height={"100%"} />
              </Col>
            </Row>
            <div style={{ marginTop: 20 }}>
              <Row>
                <Col sm="12"><Button style={{ width: "100%" }} disabled={loading} onClick={() => { setImgModalIsOpen(false) }}>Cancel</Button></Col>
              </Row>
            </div>
          </div>
        </ModalBody>
      </Modal>
      <Modal isOpen={addProductModal} centered size="lg">
        <ModalHeader >Product Info
        </ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col sm="12">
                      <List type="unstyled">
                        {
                          imgList.length > 0 ? <><h4>Product List:</h4> {imgList.map((item, id) => {
                            return <div key={id}><Button size="sm" style={{ marginRight: 20 }} onClick={() => handleDeleteImageItem(id)}>Delete</Button><li key={id}><a className={item.includes(':') ? "list-image-none" : "list-image"} onClick={() => {
                              if (!item.includes(':')) {
                                setImgName(item);
                                setImgModalIsOpen(true);
                              }
                            }}>{item}</a></li></div>
                          })}</> :
                            <li key={"empty"}>Please Upload 768x864 Images For Products, it will be limited below 1mb.</li>
                        }
                      </List>
                    </Col>
                  </Row>
                  <Row className="admin-product-list-upload-img-btn">
                    <Col sm="4">
                      <input type="file" id="uploadRealBtn" name="uploadRealBtn" accept="image/jpeg, image/png" style={{ display: 'none' }} onChange={handleFileChange} />
                      <Button color="primary" onClick={handleUploadBtnOnclick} disabled={imgList.length >= 3}>Upload</Button>
                    </Col>
                  </Row>

                  <Row>
                    <Col md="4">
                      <Label for="lName">Product Name</Label>
                      <Input type="text" className="form-control" id="product_name" name="product_name" placeholder="Product Name" onChange={onSubmitFormChange} defaultValue={formData.product_name} />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Product Price</Label>
                      <Input type="number" className="form-control" id="product_price" name="product_price" placeholder="Product Price" onChange={onSubmitFormChange}
                        defaultValue={formData.product_price} />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Product Quantity</Label>
                      <Input type="number" pattern="[0-9]*" className="form-control" id="product_num" name="product_num" placeholder="Product Quantity" onChange={onSubmitFormChange}
                        defaultValue={formData.product_quantity} />
                    </Col>
                  </Row>
                  <Row style={{ marginTop: 20, marginBottom: 10 }}>
                    <Col sm="12">
                      <Button color="primary" onClick={() => { setDetailModal(true) }}>ADD DETAIL</Button>
                      <input type="file" id="uploadExcelRealBtn" name="uploadExcelRealBtn" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style={{ display: 'none' }} onChange={handleExcelFileChange} />
                      <Button color="primary" style={{ marginLeft: 20 }} onClick={handleExcelUploadOnclick}>IMPORT EXCEL</Button>
                      <Button style={{ marginLeft: 20 }} onClick={handleDwonloadTempExcel}>Example XLSX</Button>
                      {/* <Button color="primary" style={{ marginLeft: 20 }} onClick={() => { setDetailModal(true) }}>IMPORT EXCEL</Button> */}
                    </Col>
                    <Col sm="6">
                    </Col>
                  </Row>
                  <Row>
                    <Col sm="12">
                      <div className="table">
                        <table className="table cart-table table-responsive-xs">
                          <thead>
                            <tr className="table-head">
                              {/* <th scope="col">image</th> */}
                              <th scope="col">Year</th>
                              <th scope="col">Brand</th>
                              <th scope="col">Model</th>
                              <th scope="col">Engine</th>
                              <th scope="col">Fuel Type</th>
                              <th scope="col">action</th>
                            </tr>
                          </thead>
                          {detailList.map((item, index) => {
                            return (
                              <tbody key={index}>
                                <tr>
                                  <td>
                                    <h6>{item.year}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.brand}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.model}</h6>
                                  </td>

                                  <td>
                                    <h6>{item.engine}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.fuel_type}</h6>
                                  </td>
                                  <td>
                                    <><Button onClick={() => { DeleteDetail(index) }}>Delete</Button></>
                                  </td>
                                </tr>
                              </tbody>
                            );
                          })}

                        </table>
                      </div>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="9">
                      <Label for="deliverAddress">Product Detail</Label>
                      <Input type="text" className="form-control" id="product_detail" name="product_detail" placeholder="Product Detail, Max length: 100 digits." maxLength={100}
                        required="" defaultValue={formData.product_detail} onChange={onSubmitFormChange} />
                    </Col>
                    <Col md="3">
                      <Label for="fname">Update Date</Label>
                      <div><h4>{formData.upload_date}</h4></div>
                      {/* <Input type="text" className="form-control" id="upload_date" name="upload_date" disabled defaultValue={formData.upload_date} /> */}
                    </Col>
                    <Col md="12">
                      <Label for="zipCode">Product Description</Label>
                      <Input type="textarea" style={{ height: 100 }} className="form-control" id="product_description" name="product_description" placeholder="Product Description, Max length: 400 digits." maxLength={3000}
                        required="" defaultValue={formData.product_description} onChange={onSubmitFormChange} />
                    </Col>
                  </Row>
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="6">
                      </Col>
                      <Col md="3">
                        <Button color="primary" style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} onClick={SaveNewProduct}>Save</Button>
                      </Col>
                      <Col md="3">
                        <Button onClick={() => { setAddProductModal(false); setDetailList([]) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} >Cancel</Button>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      <Modal isOpen={isOpen} centered size="lg">
        <ModalHeader >Product Info
        </ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col sm="12">
                      <List type="unstyled">
                        {
                          imgList.length > 0 ? <><h4>Product List:</h4> {imgList.map((item, id) => {
                            return <div key={id}><Button size="sm" style={{ marginRight: 20 }} onClick={() => handleDeleteImageItem(id)}>Delete</Button><li key={id}><a className={item.includes(':') ? "list-image-none" : "list-image"} onClick={() => {
                              if (!item.includes(':')) {
                                setImgName(item);
                                setImgModalIsOpen(true);
                              }
                            }}>{item}</a></li></div>
                          })}</> :
                            <li key={"empty"}>Please Upload 768x864 Images For Products, it will be limited below 1mb.</li>
                        }
                      </List>
                    </Col>
                  </Row>
                  <Row className="admin-product-list-upload-img-btn">
                    <Col sm="4">
                      <input type="file" id="uploadRealBtn" name="uploadRealBtn" accept="image/jpeg, image/png" style={{ display: 'none' }} onChange={handleFileChange} />
                      <Button color="primary" onClick={handleUploadBtnOnclick} disabled={imgList.length >= 3}>Upload</Button>
                    </Col>
                  </Row>

                  <Row>
                    <Col md="4">
                      <Label for="lName">Product Name</Label>
                      <Input type="text" className="form-control" id="product_name" name="product_name" placeholder="Product Name" onChange={onSubmitFormChange} defaultValue={formData.product_name} />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Product Price</Label>
                      <Input type="number" className="form-control" id="product_price" name="product_price" placeholder="Product Price" onChange={onSubmitFormChange}
                        defaultValue={formData.product_price} />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Product Quantity</Label>
                      <Input type="number" pattern="[0-9]*" className="form-control" id="product_num" name="product_num" placeholder="Product Quantity" onChange={onSubmitFormChange}
                        defaultValue={formData.product_quantity} />
                    </Col>
                  </Row>
                  <Row>
                    <Col sm="12">
                      <div className="table">
                        <table className="table cart-table table-responsive-xs">
                          <thead>
                            <tr className="table-head">
                              {/* <th scope="col">image</th> */}
                              <th scope="col">Year</th>
                              <th scope="col">Brand</th>
                              <th scope="col">Model</th>
                              <th scope="col">Engine</th>
                              <th scope="col">Fuel Type</th>
                              <th scope="col">action</th>
                            </tr>
                          </thead>
                          {detailList.map((item, index) => {
                            return (
                              <tbody key={index}>
                                <tr>
                                  <td>
                                    <h6>{item.year}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.brand}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.model}</h6>
                                  </td>

                                  <td>
                                    <h6>{item.engine}</h6>
                                  </td>
                                  <td>
                                    <h6>{item.fuel_type}</h6>
                                  </td>
                                  <td>
                                    <><Button onClick={() => { DeleteDetail(index) }}>Delete</Button></>
                                  </td>
                                </tr>
                              </tbody>
                            );
                          })}

                        </table>
                      </div>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="fname">Update Date</Label>
                      <div><h4>{formData.upload_date}</h4></div>
                      {/* <Input type="text" className="form-control" id="upload_date" name="upload_date" disabled defaultValue={formData.upload_date} /> */}
                    </Col>
                  </Row>
                  <Row>
                    <Col md="12">
                      <Label for="deliverAddress">Product Detail</Label>
                      <Input type="text" className="form-control" id="product_detail" name="product_detail" placeholder="Product Detail, Max length: 100 digits." maxLength={100}
                        required="" defaultValue={formData.product_detail} onChange={onSubmitFormChange} />
                    </Col>
                    <Col md="12">
                      <Label for="zipCode">Product Description</Label>
                      <Input type="textarea" style={{ height: 100 }} className="form-control" id="product_description" name="product_description" placeholder="Product Description, Max length: 400 digits." maxLength={400}
                        required="" defaultValue={formData.product_description} onChange={onSubmitFormChange} />
                    </Col>
                  </Row>
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="6">
                      </Col>
                      <Col md="3">
                        <Button color="primary" style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} onClick={SaveProductInfo}>Save</Button>
                      </Col>
                      <Col md="3">
                        <Button onClick={() => { setIsOpen(false); setDetailList([]) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} disabled={loading} >Cancel</Button>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      {/* <div>
        <Row className="admin-user-btn-list">
          <Col md="3"><Input type="text" className="form-control" id="lname" name="lname" placeholder="Please enter product name, Year, Brand..." onChange={onKeywordChange} /></Col>
          <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={SearchProduct}>Search</a></Col>
          <Col md="1"><a href={null} style={{ width: 160, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={AddProduct} >Add Product</a></Col>
        </Row>
      </div> */}
      <div>
        <Row className="order-list-filter-btn-list">
          <Col md="4">
            <ButtonGroup style={{ marginRight: 20, marginLeft: 80 }}>
              <UncontrolledDropdown>
                <DropdownToggle caret>
                  Filter
                </DropdownToggle>
                <DropdownMenu>
                  <DropdownItem active={filter == '-1'} onClick={() => { ChangeFilter(-1) }}>
                    All
                  </DropdownItem>
                  <DropdownItem active={filter == '-2'} onClick={() => { ChangeFilter(-2) }}>
                    Deleted
                  </DropdownItem>
                </DropdownMenu>
              </UncontrolledDropdown>
            </ButtonGroup>
          </Col>
          <Col md="3">
          </Col>
          <Col md="2"><Input type="text" className="form-control" id="lname" name="lname" placeholder="Please enter product name, Year, Brand..." onChange={onKeywordChange} /></Col>
          <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={SearchProduct}>Search</a></Col>
          <Col md="2"><a href={null} style={{ width: 165, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={AddProduct} >Add Product</a></Col>
        </Row>
      </div>
      {list && list.length > 0 ? (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <table className="table cart-table table-responsive-xs">
                  <thead>
                    <tr className="table-head">
                      {/* <th scope="col">image</th> */}
                      <th scope="col">product</th>
                      <th scope="col">product name</th>
                      <th scope="col">product price</th>
                      <th scope="col">product quantity</th>
                      <th scope="col">action</th>
                    </tr>
                  </thead>
                  {list.map((item, index) => {
                    return (
                      <tbody key={index}>
                        <tr>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a className="order-list-product">
                                <Media
                                  src={item.product_media1 ? `${fileServerUrl}/${item.product_media1}` : `${fileServerUrl}/products/default.jpg`}
                                  alt=""
                                />
                              </a>
                            </Link>
                          </td>
                          <td>
                            <h2>
                              <Link href={`/product-details/` + item.product_id}>
                                <a>{item.product_name}</a>
                              </Link>
                            </h2>
                          </td>
                          <td>
                            <h2 className="td-color">
                              {symbol}
                              {getTwoDecimal(item.product_price)}
                            </h2>
                          </td>

                          <td>
                            <h4>
                              {item.product_num}
                            </h4>
                          </td>
                          <td>
                            {
                              filter != '-2' &&
                              <>
                                <Button className="admin-product-acion" onClick={() => { EditProductAdmin(item) }}>Edit</Button>
                                <Button className="admin-product-acion" onClick={() => { setConfirmModel(true); setDeleteId(item.product_id); }}>Delete</Button>
                              </>
                            }
                            {
                              filter == '-2' &&
                              <>
                                <Button className="admin-product-acion" onClick={() => { setRecoverModel(true); setRecoverId(item.product_id); }}>Recover</Button>
                              </>
                            }
                          </td>
                        </tr>
                      </tbody>
                    );
                  })}
                </table>
              </Col>
            </Row>
          </Container>
          <div className="admin-page-select-btn">
            <Button className="page-select-btn1" onClick={MinusPage}>Last Page</Button><span className="page-select-label">{pageNum} IN {pageCount}</span><Button className="page-select-btn2" onClick={AddPage}>Next Page</Button>
          </div>
        </section>
      ) : (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <div>
                  <div className="col-sm-12 empty-cart-cls text-center">
                    <Media
                      src={cart}
                      className="img-fluid mb-4 mx-auto"
                      alt=""
                    />
                    <h3>
                      <strong>Product is Empty</strong>
                    </h3>
                    <h4>Add More Product.</h4>
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>
      )}
    </div>
  );
};

export default AdminProductListPage;
